
import os
import re
import sys
import time
import xlrd
import ConfigParser
from ConfigParser import DEFAULTSECT


class CaseConfigParser(ConfigParser.SafeConfigParser):
    def __init__(self):
        ConfigParser.SafeConfigParser.__init__(self)

    def optionxform(self, optionstr):
        """rewrite to enable capital in sections"""
        return optionstr

    def write(self, fp, section_list=None):
        """Write an .ini-format representation of the configuration state."""
        """Re write to delete spaces with ="""
        if self._defaults:
            fp.write("[%s]\n" % DEFAULTSECT)
            for (key, value) in self._defaults.items():
                fp.write("%s=%s\n" % (key, str(value).replace('\n', '\n\t')))
            fp.write("\n")
        if section_list is None:
            section_list = self._sections.keys()
        for section in section_list:
            fp.write("[%s]\n" % section)
            for (key, value) in self._sections[section].items():
                if key != "__name__":
                    fp.write("%s=%s\n" %
                             (key, str(value).replace('\n', '\n\t')))
            fp.write("\n")

def make_pmmeaconfig(path):
    if not os.path.exists(path):
        print "File does not exists!"
        return False

    path_str = path.split('.')
    path_str[-1] = "ini"
    new_path = '.'.join(path_str)

    cp = CaseConfigParser()
    # for FileReader
    cp.add_section("version")
    cp.set("version", 'version', "1")

    cp.set(DEFAULTSECT, 'version', "RNC16")
    cp.set(DEFAULTSECT, 'update', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))

    data = xlrd.open_workbook(path)
    sheet = data.sheets()[0]
    
    main_sections = {}
    for i in xrange(sheet.nrows):
        section = sheet.cell_value(i, 0)
        if section and re.match(r"M10[0123]\dC\d+", section):
            m = re.findall(r"M\d+", section)[0]
            if m not in main_sections.keys():
                main_sections[m] = []
            cp.add_section(section)
            cp.set(section, 'Name', sheet.cell_value(i, 1))
            module = sheet.cell_value(i, 49)
            if len(module) > 6:
                module = module[-6:]
            if module and module not in main_sections[m]:
                main_sections[m].append(module)
            cp.set(section, 'Module', module)
            cp.set(section, 'Abbreviation', sheet.cell_value(i, 2))
            descriptrion = \
                re.findall(r"Description=([^;]*)", sheet.cell_value(i, 51))[0]
            if '%' in descriptrion:
                descriptrion = descriptrion.replace('%', '%%')
            if '\n' in descriptrion:
                descriptrion = descriptrion.replace('\n', ' ')
            cp.set(section, 'Description', descriptrion)

    for var in main_sections.keys():
        section = "%sC999" % var
        cp.add_section(section)
        cp.set(section, 'Module', ','.join(main_sections[var]))

    section_dict = {}
    for var in cp.sections():
        nums = re.findall(r"M(\d+)C(\d+)", var)
        if nums:
            num = int(nums[0][0]) * 1000 + int(nums[0][1])
            section_dict["%d" % num] = var

    section_list = ["version"]
    for var in sorted(section_dict.keys()):
        section_list.append(section_dict[var])
    
    with open(new_path, 'w') as f:
        cp.write(f, section_list)

def myhelp():
    print "[Function]: This program pickup info from counter excel file "
    print "which export from http://esodts055.emea.nsn-net.net:8080/ContentViewer/."
    print "[Usage]: make_pmmeaconfig.py file.xls"

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print "Error: No input Excel file specified."
        myhelp()
        sys.exit()

    path = sys.argv[1]
    if path == "help" or path == "-h" or path == "--help":
        myhelp()
        sys.exit()
    else:
        make_pmmeaconfig(path)